package org.tuoren.official.service.impl;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.dromara.easyes.annotation.IndexName;
import org.dromara.easyes.core.biz.EsPageInfo;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Service;
import org.tuoren.common.core.domain.R;
import org.tuoren.common.core.utils.MapstructUtils;
import org.tuoren.common.es.properties.EasyEsProperties;
import org.tuoren.common.mybatis.core.page.PageQuery;
import org.tuoren.common.mybatis.core.page.TableDataInfo;
import org.tuoren.official.domain.Product;
import org.tuoren.official.domain.TNewsCenter;
import org.tuoren.official.domain.bo.ProductBo;
import org.tuoren.official.domain.vo.ProductVo;
import org.tuoren.official.es.domain.ArticleDetailEs;
import org.tuoren.official.es.domain.ProductEs;
import org.tuoren.official.es.domain.TNewsCenterES;
import org.tuoren.official.es.esmapper.EsProductMapper;
import org.tuoren.official.mapper.ProductMapper;
import org.tuoren.official.service.IProductESService;
import org.tuoren.official.service.IProductService;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品信息Service业务层处理
 *
 * @author wl
 * @date 2024-11-26
 */
@RequiredArgsConstructor
@Service
public class ProductEsServiceImpl implements IProductESService {

    private final ProductMapper baseMapper;
    private final EsProductMapper esMapper;
    private final EasyEsProperties easyEsProperties;


    @Override
    public R<Void> initData() {
        if (!easyEsProperties.getEnable()) {
            return R.fail("系统ES服务未打开！");
        }
        //1.先检查是否存在索引,存在就删除
        checkIndexExistAndRemove();
        //2.创建索引
        Boolean created = esMapper.createIndex();
        if (!created) {
            return R.fail("创建ES索引失败！");
        }
        //2.构建es数据
        List<Product> voList = baseMapper.selectList();
        List<ProductEs> newsProductEsList = voList.stream().map(blog -> {
            ProductEs productEs =  BeanUtil.toBean(blog, ProductEs.class);
            return productEs;
        }).collect(Collectors.toList());
        //3.插入ES
        Integer count = esMapper.insertBatch(newsProductEsList);
        return count == newsProductEsList.size() ? R.ok("初始化成功："+count+"条产品信息"):R.fail("创建ES索引失败！");
    }

    @Override
    public TableDataInfo<ProductEs> searchList(String searchText, PageQuery pageQuery) {
        LambdaEsQueryWrapper<ProductEs> wrapper = new LambdaEsQueryWrapper<>();
        if (StringUtils.isNotBlank(searchText)){
            wrapper.and(iwrapper ->wrapper.like(ProductEs::getName,searchText.toLowerCase())
                .or()
                .like(ProductEs::getDescribes,searchText.toLowerCase())
                .or()
                .like(ProductEs::getSummary,searchText.toLowerCase()));
        }
        List<ProductEs> articleDetailEs = esMapper.selectList(wrapper);
        Long l = esMapper.selectCount(wrapper);
        System.out.println(l);
        System.out.println(JSONObject.toJSONString(articleDetailEs));
        EsPageInfo<ProductEs> esPageInfo = esMapper.pageQuery(wrapper, pageQuery.getPageNum(), pageQuery.getPageSize());
        TableDataInfo tableDataInfo = new TableDataInfo(esPageInfo.getList(), esPageInfo.getTotal());
        tableDataInfo.setCode(HttpStatus.HTTP_OK);
        tableDataInfo.setMsg("查询成功");
        System.out.println(JSONObject.toJSONString(esPageInfo));
        return tableDataInfo;
    }
    /**
     * 查找ES中是否存在索引，存在删除该索引
     */
    private void checkIndexExistAndRemove() {
        IndexName indexName = AnnotationUtil.getAnnotation(ProductEs.class, IndexName.class);
        //索引名称--如 blog_news
        String indexNameValue = indexName.value();
        Boolean existIndex = esMapper.existsIndex(indexNameValue);
        if (existIndex) {
            esMapper.deleteIndex(indexNameValue);
        }
    }
}
